package com.ziq.zcamp.community

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.GsonUtils
import com.ziq.base.extension.launchWithTryAsyncGlobal
import com.ziq.zcamp.api.request.common.BannerListParam
import com.ziq.zcamp.api.request.post.PostingRecommendListParam
import com.ziq.zcamp.api.respond.common.BannerListRespond
import com.ziq.zcamp.api.respond.post.PostingRecommendListRespond
import com.ziq.zcamp.api.service.CommonService
import com.ziq.zcamp.api.service.PostingService
import com.ziq.zcamp.api.service.request
import com.ziq.zcamp.bean.common.BannerResult
import com.ziq.zcamp.bean.post.ImageInfo
import com.ziq.zcamp.bean.post.PostingDetail
import com.ziq.zcamp.view.StatusView
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject

@HiltViewModel
class CommunityRecommendViewModel @Inject constructor() : ViewModel() {

    @Inject
    lateinit var mPostingService: PostingService

    @Inject
    lateinit var mCommonService: CommonService

    val statusShow = MutableLiveData<Int>()
    val listRequestFinished = MutableLiveData<Boolean>()
    val listHasMore = MutableLiveData<Boolean>()
    val list = MutableLiveData<MutableList<PostingDetail>>()
    val bannerList = MutableLiveData<MutableList<BannerResult.BannerItem>>()

    var lastRefreshTime = 0L

    var cursor :String? = null
    //postValue存在延迟，所以用这个判断
    private var listIsEmpty = true

    fun onRefresh(showProgress: Boolean = false){
        cursor = null
        if(showProgress){
            statusShow.postValue(StatusView.LOADING)
        }
        requestList()
        requestBanner()
    }

    fun onLoadMore(){
        requestList()
    }

    fun requestList() {
        launchWithTryAsyncGlobal(whenTry = {
            val respond = mPostingService.postingRecommendList(PostingRecommendListParam().apply {
                this.cursor = this@CommunityRecommendViewModel.cursor?:""
                this.page_size = 20
            }.queryMap).request()

            if(respond.data?.list?.isNotEmpty() == true){
                for(item in respond.data?.list!!){
                    item.parseData()
                }
            }

            requestSuccess(respond)
        }, whenCatch = {
            it.printStackTrace()
            withContext(Dispatchers.Main) {
                requestFail()
            }
        })
    }

    private fun requestSuccess(it: PostingRecommendListRespond){
        if (it.data != null){
            val tempList = mutableListOf<PostingDetail>()
            if(!cursor.isNullOrEmpty() && list.value != null){
                tempList.addAll(list.value!!)
            }
            if(it.data?.list?.isNotEmpty() == true){
                for (item in it.data!!.list!!){
                    if(!tempList.contains(item)){
                        tempList.add(item)
                    }
                }
            }

            listIsEmpty = tempList.isEmpty()
            list.postValue(tempList)

            cursor = it.data?.cursor

            if(it.data?.has_more == true){
                listHasMore.postValue(true)
            } else {
                listHasMore.postValue(false)
            }

            if(tempList.isNotEmpty()){
                statusShow.postValue(StatusView.IDLE)
            }else {
                statusShow.postValue(StatusView.NO_DATA)
            }
        }else {
            if(cursor.isNullOrEmpty()){
                statusShow.postValue(StatusView.NET_ERROR)
            } else {
                statusShow.postValue(StatusView.IDLE)
            }
            listHasMore.postValue(false)
        }
        listRequestFinished.postValue(true)
    }

    private fun requestFail() {
        if(cursor.isNullOrEmpty() && listIsEmpty){
            statusShow.postValue(StatusView.NET_ERROR)
        } else {
            statusShow.postValue(StatusView.IDLE)
        }
        listRequestFinished.postValue(true)
    }

    private fun requestBanner(
        onSuccess: ((result: BannerListRespond) -> Unit)? = {
            if(it.data != null){
                bannerList.postValue(it.data?.list)
            }
        },
        onFail: ((result: String) -> Unit)? = {
        }) {

        launchWithTryAsyncGlobal(whenTry = {
            val respond = mCommonService.bannerList(BannerListParam().queryMap).request()
            if(respond.data?.list?.isNotEmpty() == true){
                for(item in respond.data?.list!!){
                    var imageList: List<ImageInfo> =  mutableListOf<ImageInfo>()
                    if (item.pictures?.isNotEmpty() == true){
                        item.pictures?.let {
                            imageList = GsonUtils.fromJson(it, GsonUtils.getListType(
                                ImageInfo::class.java))
                        }
                    }
                    item.images = imageList
                }
            }
            onSuccess?.invoke(respond)
        }, whenCatch = {
            withContext(Dispatchers.Main) {
                onFail?.invoke("$it")
            }
        })
    }

}